/**
 * @Author kjprime
 * @description redis4.0数据库模块
 */
const redis = require('redis')
const redis_config = {
    host: process.env.REDIS_HOST,
    port: process.env.REDIS_PORT,
    password: process.env.REDIS_PASSWORD,
    number: process.env.REDIS_NUMBER,
}

const url = `redis://:${redis_config.password}@${redis_config.host}:${redis_config.port}/${redis_config.number}`

const redisClient = redis.createClient({'url': url})

redisClient.on('ready', () => {
    console.log('redis is ready...')
})

redisClient.on('error', err => {
    console.error(err)
})

async function fun(callback, key, value) {
    return new Promise(async (res, rej) => {
        await redisClient.connect()     // 连接
        let ok = callback(key, value)   // 成功ok
        await redisClient.quit()        // 关闭
        res(ok)
    })
}

const db = {
    async set(key, value) {
        return fun(async () => {
            return await redisClient.set(key, value)
        }, key, value)
    },
    async get(key) {
        return fun(async () => {
            return await redisClient.get(key)
        }, key)
    },
    async del(key) {
        return fun(async () => {
            return await redisClient.del(key)
        }, key)
    },
}

module.exports = db